package com.kinth.dbutil;

/**
 * 实现InterfaceDB的接口，调用DBConnect获取链接。然后提供增删改查的一般性函数接口。详细说明参考InterfaceDB
 */
import java.sql.*;
import java.util.ArrayList;

import com.kinth.work.webmagic.huicong.UrlHuiCong;
import com.kinth.work.webmagic.huicong.dbUtil;



public class ImplDAO implements InterfaceDB {

	
	
	public ImplDAO() {
		//conn = C3P0Utils.getInstance().getConnection();
		
	}

	public static void main(String[] args) {

		ArrayList<UrlHuiCong> urlList = dbUtil.queryUrl("huicong_url1", 5, 5);
		System.out.println("测试: "+urlList.size());
	}

	@Override
	public ArrayList<String[]> doQuery(String sql, String[] params)  {
		// TODO Auto-generated method stub
		
		PreparedStatement ps = null;
		ResultSet rs = null;
		Connection conn = null;
		DBConnect dbc = new DBConnect();
		conn = //C3P0Utils.getInstance().getConnection();
				dbc.getConn();
		
		ArrayList<String[]> all = new ArrayList<String[]>();
		try
		{
			if (params == null || params.length == 0) {
				
				ps = conn.prepareStatement(sql);
				rs = ps.executeQuery();
			
			
		} else {

			
				ps = conn.prepareStatement(sql);
				for (int i = 0; i < params.length; i++) {

					ps.setString(i + 1, params[i]);
				}
				rs = ps.executeQuery();
			

		}
		ResultSetMetaData rsmd = rs.getMetaData();
		int column = rsmd.getColumnCount();

		while (rs.next()) {
			String arrTemp[] = new String[column];
			for (int i = 0; i < column; i++) {
				arrTemp[i] = rs.getString(i + 1);
			}
			all.add(arrTemp);
		}
	
		}catch(Exception e)
		{
			e.printStackTrace();
		}finally
		{
			try
			{
				if(ps!=null)
				{
					ps.close();
				}
				
				
			} catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			dbc.closeConn();
			//C3P0Utils.releaseConnection(conn);
		}
		
		return all;
	}

	@Override
	public boolean doExecute(String sql, String[] params)  {
		PreparedStatement ps = null;
		ResultSet rs = null;
		DBConnect dbc = new DBConnect();
		Connection conn = dbc.getConn();
				//C3P0Utils.getInstance().getConnection();
		
		boolean flag = true;
		try
		{
			if (params == null || params.length == 0) {
				ps = conn.prepareStatement(sql);
				ps.executeUpdate();
			} else {

				ps = conn.prepareStatement(sql);
				for (int i = 0; i < params.length; i++) {

					ps.setString(i + 1, params[i]);
				}
				ps.executeUpdate();

			}
			
		}catch(Exception e)
		{
			//e.printStackTrace();
			System.out.println("重复插入");
		}finally{
			try
			{
				ps.close();
				//C3P0Utils.releaseConnection(conn);
				dbc.closeConn();
			} catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//db.closeConn();
			
		}
		
		return flag;
	}

}
